<template>
  <a-spin class="poi-list" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter">
      <div class="l" style="display:flex;flex-wrap: wrap;">
        <div>
          <span>状态：</span>
          <a-select style="width:160px" placeholder="请选择状态" v-model="search.status" @change="handleByQueryCond">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">待审核</a-select-option>
            <a-select-option value="1">已通过</a-select-option>
            <a-select-option value="2">已驳回</a-select-option>
          </a-select>
        </div>
        <div style="margin-left:15px;">
          <span>绑定时间：</span>
          <a-range-picker style="margin-right:15px;" @change="handleByQueryCond" v-model="search.selectDate" />
        </div>
      </div>

      <div class="r" style="width:200px;">
        <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9">查询</a-button>
        <a-button type="primary" @click="addBinding" style="background:#34C025;border-color:#34C025;margin-left:15px;">+ 新增视频</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="main-body">
      <a-table :columns="tableColumns" :pagination="false" :data-source="productList" :scroll="{ x: 900, y: tableHeight }" rowKey="id">
        <template slot="status" slot-scope="text, record">
          <span :class="[record.status === 2 ? 'color-f55' : null]">
            {{ record.statusStr || '--' }}
            <a-tooltip v-if="record.status === 2">
              <template slot="title">
                {{ record.rejectReson }}
              </template>
              <a-icon type="info-circle" class="color-f55" />
            </a-tooltip>
          </span>
        </template>
      </a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="pagination.pageSize"
        v-model="pagination.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;text-align:right;"
        @change="handlePageChange"
      />
    </div>
    <!-- 新增视频绑定 -->
    <a-modal class="copy-modal" width="500px" :footer="null" :visible="vedioBindingShow" @cancel="cancleSubmitAddVedio()" title="新增绑定视频">
      <a-spin tip="提交中..." :spinning="isBindVedioLoading">
        <a-form-model ref="vedioBindingForm" :model="vedioBindingForm" :rules="addvedioRules" :label-col="{ span: 4 }" :wrapper-col="{ span: 19 }">
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="视频链接" prop="videoUrl"> <a-input v-model="vedioBindingForm.videoUrl" placeheloder="请输入主播抖音视频链接"></a-input></a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="视频ID" prop="videoId"> <a-input v-model="vedioBindingForm.videoId" placeheloder="请输入主播抖音视频ID"></a-input></a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="备注">
                <a-input v-model="vedioBindingForm.remark" type="textarea" :maxLength="50"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div style="display:flex;justify-content: center;">
          <a-button type="" @click="cancleSubmitAddVedio()" style="margin-right:20px;">取消</a-button>
          <a-button type="primary" @click="submitAddVedio()" style="margin-right:20px;">提交审核</a-button>
        </div>
      </a-spin>
    </a-modal>
  </a-spin>
</template>

<script>
import { agentVideoList, locationList, bindVideoData } from '@/service'
import upload from '@/components/upload/upload'
import moment from 'moment'
import Title from '../anchorManagDesc/components/Title'
const vedioForm = function(row = {}) {
  return {
    agentId: row.agentId || 0,
    remark: row.remark || '',
    videoId: row.videoId || '',
    videoUrl: row.videoUrl || ''
  }
}
export default {
  name: 'vedioList',
  data() {
    return {
      moment,
      // 主播id
      agentId: 0,
      // loading是否显示
      isLoading: false,
      isBindVedioLoading: false,
      // 新增视频绑定
      vedioBindingShow: false,
      vedioBindingForm: vedioForm(),
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      addvedioRules: {
        videoUrl: [
          {
            required: true,
            message: '请输入主播抖音视频链接',
            trigger: 'blur'
          }
        ],
        videoId: [
          {
            required: true,
            message: '请输入主播抖音视频ID',
            trigger: 'blur'
          },
          {
            pattern: /^[a-zA-Z0-9_]*$/,
            message: '主播抖音视频ID格式有误',
            trigger: 'blur'
          },
          { min: 0, max: 20, message: '超出ID长度', trigger: 'blur' }
        ]
      },
      // table数据查询条件
      search: {
        status: '',
        selectDate: []
      },
      // 产品列表
      productList: [],
      // 主播列表总数据条数
      anchorTotal: 0,
      locationListData: []
    }
  },

  components: {
    upload,
    Title
  },

  computed: {
    // table配置
    tableColumns() {
      return [
        { title: '主播名称', width: 200, dataIndex: 'agentName' },
        { title: '主播UID', width: 200, dataIndex: 'dyUid' },
        { title: '联系电话', width: 260, dataIndex: 'phoneNumber' },
        { title: '视频链接', width: 400, dataIndex: 'videoUrl' },
        { title: '视频ID', width: 200, dataIndex: 'videoId' },
        { title: '绑定时间', width: 200, dataIndex: 'createTime' },
        { title: '状态', width: 120, fixed: 'right', dataIndex: 'status', scopedSlots: { customRender: 'status' } }
      ]
    }
  },

  methods: {
    // 站点列表
    async getLocationList() {
      await locationList({ city: '' }).then((res = []) => {
        this.locationListData = res
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.pagination.pageIndex = 1
      this.query()
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.pagination.pageIndex = num
      this.query()
    },

    // 拿参数
    getParams() {
      const { pageIndex, pageSize } = this.pagination
      const { selectDate, status } = this.search

      return {
        pageIndex,
        pageSize,
        status,
        agentId: this.agentId,
        startTime: selectDate[0] ? moment(selectDate[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        endTime: selectDate[1] ? moment(selectDate[1]).format('YYYY-MM-DD 23:59:59') : undefined
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, startTime, endTime, status, agentId } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          status: status || '',
          agentId: agentId || this.agentId || 0,
          selectDate: startTime && endTime ? [moment(Number(startTime)), moment(Number(endTime))] : []
          //  selectDate: beginTime ? Number(beginTime) : null,
          //  endTime: endTime ? Number(endTime) : null,
        }
      }
    },
    // 初始化
    initQuery() {
      this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 获取产品列表
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      agentVideoList(this.getParams())
        .then((rs) => {
          this.productList = Object.freeze(rs.agentVideoListData) || []
          this.pagination.total = rs.total || 0
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key]) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    // 新增绑定
    addBinding() {
      this.vedioBindingShow = true
    },
    cancleSubmitAddVedio() {
      this.vedioBindingShow = false
      this.vedioBindingForm = vedioForm({})
      let form = this.$refs.vedioBindingForm
      if (form && form.clearValidate) {
        this.$nextTick(() => {
          form.clearValidate()
        })
      }
    },
    submitAddVedio() {
      this.vedioBindingForm.agentId = this.agentId
      this.$refs.vedioBindingForm.validate((valid, obj = {}) => {
        if (valid) {
          this.isBindHostLoading = true
          bindVideoData(this.vedioBindingForm)
            .then((res) => {
              this.query()
              this.vedioBindingShow = false
              this.vedioBindingForm = vedioForm({})
            })
            .finally(() => {
              this.isBindVedioLoading = false
            })
            .catch(() => {
              this.isBindVedioLoading = false
            })
        }
      })
    }
  },

  mounted() {
    const { id = 0 } = this.$route.query || {}
    this.agentId = id
    this.getLocationList()
    this.setSearch()
    this.query()
  },

  filters: {
    // 处理分-元
    fenToYuan(val) {
      if (!val) return 0
      return (val / 100).toFixed(2)
    }
  }
}
</script>

<style lang="less" scoped>
.poi-list {
  padding: 16px;
}
.margin-bott-10 {
  margin-bottom: 10px;
}
.id-card-box {
  display: flex;
  &-item {
    text-align: center;
    p {
      margin-right: 8px;
      margin-top: -20px;
    }
  }
}
.color-f55 {
  color: #f55f4e !important;
}
</style>
